import React from 'react';
import {connect} from 'react-redux';
import {Form, Tabs, Spin, Button, Icon, Switch, Radio, Row, Col, Collapse, Popconfirm, message} from 'antd';
const FormItem = Form.Item;
import {messages} from "share/common";
const TabPane = Tabs.TabPane;
import Selector from 'components/selector'
import 'styles/setting/notification-setting/notification.scss';
import Chooser from 'components/chooser'
import LanguageInput from 'components/template/language-input/language-input'
const RadioGroup = Radio.Group;
const Panel = Collapse.Panel;
import notificationContentService from "containers/setting/notification-setting/notification-content/notification-content.service"
import config from 'config'
class MessagesSetting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      pageLoading: false,
      status: 'approve-remind',
      tabs: [
        {key: 'approve-remind', name: messages('setting.key1561')/*审批提醒*/},
      ],
      ruleId: '',
      isEdit: false,
      messageForm: [],
      remindList: [],
      params: {
        i18n: {},
        ruleId: '',
        title: null,
        content: null,
        visibleCompanyScope: 1,
        valid: true,
      },
      contentInRule: [],
      titleInRule: [],
      notificationMethod: {},
    };
  }

  componentWillMount() {
    this.setState({
      messageForm: this.props.messageForm,
      type: this.props.type,
    }, () => {
      this.getRemindList();
    });
    const {languageList,} = this.props;
    let list = {};
    notificationContentService.getNotificationRulesMethods()
      .then(res => {
        res.data.forEach(item => {
          list[item.value] = item.messageKey;
        })
        this.setState({
          notificationMethod: list
        })
      })
    languageList.map(language => {
      if (language.code.toLowerCase() === this.props.language.code.toLowerCase()) {
        this.state.contentInRule.push({
          language: language.code.toLowerCase(),
          length: 200,
        });
        this.state.titleInRule.push({
          language: language.code.toLowerCase(),
          length: 50,
        });
      }
    })
  }

  componentWillReceiveProps = (nextProps) => {
    this.setState({
      messageForm: nextProps.messageForm,
      type: this.props.type,
    },()=>{
      this.refreshTitleAndContent()
    })
  }

  handleNew = () => {
    this.setState({
      isEdit: true,
    },this.refreshTitleAndContent())
  };

  getDefaultValue = item => {
    if (item.type === 'select' && item.defaultValue && item.defaultValue.key)
      return item.defaultValue.key;
    else
      return item.defaultValue;
  };

  handCancel = () => {
    this.setState({
      isEdit: false,
    })
  };

  handleSelectCompany = (value) => {
    let params = this.state.params;
    let companyArr = [];
    let companyValue = []
    value.forEach(item => {
      companyArr.push(item.companyOID);
      companyValue.push(item);
    });
    params.companyOIDList = companyArr;
    params.customCompanyRelationResps = companyValue;
    this.setState({
      params
    });
  };

  handleNewSheetContentChange = (value, i18n, textArea,item) => {
    let params = this.state.params;
    if (textArea) {
      if(item.content){
        item.content = value
      }
      params.content = value;
      params.i18n.content = i18n;
    } else {
      if(item.title){
        item.title = value
      }
      params.title = value;
      params.i18n.title = i18n;
    }
    this.setState({params})
  };

  handleAddTab = (res, item) => {
    const {languageList} = this.props;
    let params = this.state.params;
    if (item.textArea) {
      if(item.content){
        item.content = item.content+'#' + res.code+'#';
        params.content = item.content;
      }else{
        params.content = params.content +'#'+res.code+'#';
      }
      params.i18n.content = [];
      languageList.map(language => {
        if (language.code.toLowerCase() === this.props.language.code.toLowerCase()) {
          params.i18n.content.push({
            language: language.code.toLowerCase(),
            value: `${params.content}`
          })
        }
      })
    } else {
      if(item.title){
        item.title = item.title +'#'+ res.code+'#';
        params.title = item.title;
      }else{
        params.title = params.title+'#' +res.code+'#';
      }

      params.i18n.title = [];
      languageList.map(language => {
        if (language.code.toLowerCase() === this.props.language.code.toLowerCase()) {
          params.i18n.title.push({
            language: language.code.toLowerCase(),
            value: `${params.title}`
          })
        }
      })
    }
    this.setState({params})
  };


  handleChangeCompany = (e) => {
    let params = this.state.params;
    params.visibleCompanyScope = e.target.value;
    this.setState({
      params
    });
  };


  handleRegulation = (res) => {
    let params = this.state.params;
    if(!!res.length){
      params.ruleId = res[0].id;
      params.remindRegulationDTO = res[0];
      this.setState({
        params,
      });
    }else{
      params.ruleId = null;
      params.remindRegulationDTO = null;
      this.setState({
        params,
      });
    }

  };

  handleChangeStatus = (res) =>{
    let params = this.state.params;
    params.valid = res;
    this.setState({
      params,
    });
  };

  renderFormItem(item,index) {
    let {params, contentInRule, titleInRule} = this.state;
    let selectorItem = {
      title: messages('setting.key1636',{arg1:item.label})/*选择{arg1}*/,
      url: `${config.baseUrl}/api/remind/regulation/list?triggerType=${this.state.type === 2 ? 'AUTO' : 'MANUAL'}`,
      searchForm: [
        {type: 'input', id: 'regulationCode', label: messages('setting.key1564')/*提醒规则代码*/},
        {type: 'input', id: 'regulationName', label: messages('setting.key1565')/*提醒规则名称*/}
      ],
      columns: [
        {title: messages('setting.key1564')/*提醒规则代码*/, dataIndex: 'regulationCode'},
        {title: messages('setting.key1091')/*规则名称*/, dataIndex: 'regulationName'},
      ],
      key: 'id'
    };
    switch (item.type) {
      case 'switch': {
        // return <Switch checked={params.valid}/>
        return (
          <Row className="marginBottom-30" key={index}>
            <Col className="marginBottom-10">
              <span style={{color: '#f5222d'}}>*</span>{item.label}：
            </Col>
            <Col> <Switch checked={params.valid} onChange={this.handleChangeStatus}/></Col>
          </Row>
        )
      }
      case 'chooser': {
        return (
          <div className="marginBottom-30" key={index}>
            <Row className="marginBottom-10">
              <span style={{color: '#f5222d'}}>*</span>{item.label}：
            </Row>
            <Row>

              <Chooser style={{marginTop: '30px', width: '50%'}} placeholder={messages('common.please.select')}
                       labelKey='regulationName'
                       valueKey='regulationCode'
                       selectorItem={selectorItem}
                       value={params.remindRegulationDTO?[params.remindRegulationDTO]:null}
                       onChange={this.handleRegulation}
                       single={true}/>
            </Row>
          </div>
        )
      }
      case 'radio-company': {
        return (
          <div className="marginBottom-30" key={index}>
            <Row className="marginBottom-10">
              {messages('setting.key486'/*适用公司*/)}：
            </Row>
            <Row span={6}>
              <RadioGroup value={params.visibleCompanyScope} onChange={this.handleChangeCompany}>
                {item.options.map((option) => {
                  return <Radio value={option.value} key={option.value}>{option.label}</Radio>
                })}
              </RadioGroup>
              {params.visibleCompanyScope === 2 &&
              <div style={{marginTop: '30px'}}>
                <Chooser style={{marginTop: '30px'}} placeholder={messages('common.please.select')}
                         type='available_company'
                         labelKey='name'
                         valueKey='companyOID'
                         onChange={this.handleSelectCompany}
                         value={params.customCompanyRelationResps}
                         single={false}/>

              </div>
              }
            </Row>
          </div>
        )
      }
      case 'languageInput': {
        let content = item.content ? item.content : params.content;
        let title = item.title ? item.title : params.title;
        return (
          <div className="marginBottom-30" key={index}>
            <Row className="marginBottom-10">
              <span style={{color: '#f5222d'}}>*</span> {item.label}：
            </Row>
            {item.contentText && <Row className="marginBottom-10">{item.contentText}</Row>}
            {item.contentArr && <div className="marginBottom-10">
              {item.contentArr.map((tab, index) => {
                return (<span onClick={()=>this.handleAddTab(tab,item)} className="tab-item" key={index + tab.code }>{tab.name}({tab.code})</span>)
                })
              }
            </div>
            }
            <Row>
              <LanguageInput key={item.id}
                             isEdit
                             inpRule={item.textArea ? contentInRule : titleInRule}
                             placeholder={messages('common.please.input')/*请输入*/}
                             value={item.textArea ? content : title}
                             name={item.textArea ? content : title}
                             i18nName={item.textArea ? (params.i18n.content ? params.i18n.content : null) : (params.i18n.title ? params.i18n.title : null)}
                             nameChange={(value, i18n) => this.handleNewSheetContentChange(value, i18n, item.textArea,item)}
                             textArea={item.textArea}
              />
            </Row>
          </div>
        )
      }

    }
  }

  refreshTitleAndContent = () =>{
   let  params = {
      i18n: {},
      ruleId: '',
        id: null,
        title: null,
        content: null,
        visibleCompanyScope: 1,
        valid: true,
        companyOIDList: null,
        customCompanyRelationResps: null,
        remindRegulationDTO:null
    };
    this.state.messageForm.map((item,index) => {
      switch (item.type) {
        case 'languageInput':
          if(item.textArea){
            params.content = item.content
          }else{
            params.title = item.title
          }
          this.setState({
            params
          })

      }
    })
  }

  getRemindList = () => {
    this.setState({
      pageLoading: true,
    });

    let params = {type: this.state.type};
    notificationContentService.getRemindList(params)
      .then((res) => {
        this.setState({
          remindList: res.data,
          pageLoading: false,
        })
      }).catch(err => {
      this.setState({
        pageLoading: false,
      });
      if (err.response) {
        message.error(err.response.data.message);
      } else {
        message.error(messages('common.error'));
      }
    });
  }

  submitData = (method, account) => {
    notificationContentService[method](account)
      .then((res) => {
        if (res.status === 200) {
          this.setState({
            isEdit: false,
            loading: false,
          }, () => {
            this.getRemindList();
          })
        } else {
          this.setState({
            loading: false,
          })
        }

      }).catch(err => {
      this.setState({
        loading: false,
      });
      if (err.response) {
        message.error(err.response.data.message);
      } else {
        message.error(messages('common.error'));
      }
    });
  }


  //保存
  handSubmit = (e) => {
    e.preventDefault();
    const {params,type} = this.state;
    if (params.title === '') {
      message.error(messages('common.please.enter') + messages('setting.key79')/*提醒标题*/);

      return;
    } else if (params.content === '') {
      message.error(messages('common.please.enter') + messages('setting.key744')/*提醒内容*/);
      return;
    } else if (params.visibleCompanyScope === 2 && (!params.customCompanyRelationResps || params.customCompanyRelationResps.length === 0)) {
      message.error(messages('common.please.select') + messages('setting.key837')/*公司*/);
      return;
    } else if (params.ruleId === '' || !params.ruleId) {
      message.error(messages('common.please.select') + messages('setting.key1566')/*提醒规则*/);
      return;
    }
    this.setState({
      loading: true,
    });
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let account = Object.assign({}, params, values);
        account.type = type;
        if (account.id) {
          this.submitData('putSaveRemind', account);
        } else {
          this.submitData('postSaveRemind', account);
        }
      }
    });
  };

  handleEdit(e, item) {
    e.stopPropagation();
    if(!item.i18n){
      item.i18n={};
    }
    this.setState({
      isEdit: true,
      params: item
    })
  }

  handleDelete(item) {
    notificationContentService.deleteRemind([item.id])
      .then(res => {
        if (res.data) {
          this.getRemindList();
        }
      })
  }

  analyzeRule(remindRegulationDTO) {
    let weekDate = {
      MON: messages('setting.key1567')/*每周一*/,
      TUE: messages('setting.key1568')/*每周二*/,
      WED: messages('setting.key1569')/*每周三*/,
      THU: messages('setting.key1570')/*每周四*/,
      FRI: messages('setting.key1571')/*每周五*/,
      SAT: messages('setting.key1572')/*每周六*/,
      SUN: messages('setting.key1573')/*每周日*/,
    }
    let remindDayArr = [];
    let remindDays = ''
    let remindClientsArr = [];
    let remindClients = '';
    remindRegulationDTO.remindDays.forEach(item => {
      remindDayArr.push(weekDate[item]);
    })
    remindDays = remindDayArr.join('、');
    remindRegulationDTO.remindClients.forEach(item => {
      remindClientsArr.push(this.state.notificationMethod[item]);
    })
    remindClients = remindClientsArr.join('、');
    return (
      <div className="notification-rule">
        {!!remindRegulationDTO.remindTimes.length &&
        <div>{messages('setting.key743')/*提醒时间*/}：{remindRegulationDTO.remindTimes.join('、')}</div>
        }
        {!!remindDayArr.length && <div>{messages('setting.key1574')/*重复提醒*/}：{remindDays}</div>}
        <div>{messages('setting.key88')/*提醒方式*/}：{remindClients}</div>
      </div>

    )
  }

  render() {
    const {tabs, status, pageLoading, isEdit, loading, remindList, notificationMethod,type} = this.state;
    const {getFieldDecorator} = this.props.form;
    const {tenantMode} =this.props;
    const formItemLayout = {
      labelCol: {span: 24},
      wrapperCol: {span: 12}
    };
    const formItemLayoutSwitch = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 2},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
      },
    };
    return (
      <Spin spinning={pageLoading}>
        <div className="notification-setting">
          <div className="header">1、{messages('setting.key1576')/*消息提醒可引用已配置的提醒规则*/}<br/>
            2、{messages('setting.key1577')/*使用提醒规则，请先前往配置*/}<br/>
            {type === 3 &&<span>3、{messages('setting.key1696')/*当同一公司配置有多个模板时，仅有最后一个模板生效*/}</span>}
          </div>
          {!isEdit && remindList && this.state.remindList.map((item, i) => {
            let arr = [];
            if (item.customCompanyRelationResps) {
              item.customCompanyRelationResps.forEach(list => {
                arr.push(list.name)
              });
            }
            let companys = "";
            companys = (item.visibleCompanyScope === 1 ? messages('common.all')/*全部*/ : arr.join('、')  );
            let panelHeader = (
              <div className="beep-info-header">
                <span style={{whiteSpace: 'pre-wrap'}}  dangerouslySetInnerHTML={{
                  __html: item.title}}></span>
                {
                  tenantMode &&
                  <span className="beep-info-operation">
                    <a onClick={e => {this.handleEdit(e, item)}}>{messages('common.edit')/* 编辑 */}</a>
                    <span className="ant-divider"/>
                    <Popconfirm onConfirm={() => {this.handleDelete(item)}} onClick={e => e.stopPropagation()}
                                title={messages('setting.key23'/*你确定要删除这条数据吗?*/)}>
                      <a>{messages('common.delete')/* 删除 */}</a>
                    </Popconfirm>
                  </span>
                }
              </div>
            );
            return (
              <Collapse key={item.id} bordered={false}>
                <Panel header={panelHeader}>
                  <div  style={{whiteSpace: 'pre-wrap'}}  dangerouslySetInnerHTML={{
                    __html: item.type===2?`${messages('setting.key1578')/*您有（待审批单据数量）张单据等待审批*/}，${item.content}`:item.content}}></div>
                  <div>{messages('setting.key730')/*适用公司*/}：{companys}</div>
                  {notificationMethod &&item.remindRegulationDTO && this.analyzeRule(item.remindRegulationDTO)}
                </Panel>
              </Collapse>
            )
          })}
          {!isEdit && tenantMode && <Button type="dashed" className="btn-add" onClick={this.handleNew}><Icon
            type="plus"/>{messages('common.add')}{/*添加*/}</Button>
          }
          {isEdit && <Form onSubmit={this.handSubmit} className="message-form">{
            this.state.messageForm.map((item,index) => {
                return (
                  this.renderFormItem(item,index)
                )
              }
            )
          }
            <Row>
              <FormItem wrapperCol={{offset: 0}}>
                <Button type="primary" htmlType="submit" loading={loading}
                        style={{marginRight: '10px'}}>{messages('common.save') /* 保存 */}</Button>
                <Button onClick={this.handCancel}>{messages('common.cancel')/*取消(*/}</Button>
              </FormItem>
            </Row>
          </Form>
          }
        </div>
      </Spin>
    )
  }

}


MessagesSetting.propTypes = {
  messageForm: React.PropTypes.array,
  type:React.PropTypes.number,
};

MessagesSetting.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    language: state.main.language,
    languageList: state.login.languageList,
  }
}


const wrappedMessagesSetting = Form.create()(MessagesSetting);

export default connect(mapStateToProps)(wrappedMessagesSetting)

